package de.pixel83.piecemaster;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import de.pixel83.piecemaster.ai.Ai;
import de.pixel83.piecemaster.ai.MasterAi;
import de.pixel83.piecemaster.ai.MasterAi2;
import de.pixel83.piecemaster.ai.MasterAi3;
import de.pixel83.piecemaster.ai.MasterAiMichi;
import de.pixel83.piecemaster.ai.NotSoRandomAi;
import de.pixel83.piecemaster.ai.RandomAi;

// Copyright (c) 2012 Christian Kollross / Michael Freymueller

public class PieceMaster {

	public static void main(String[] args) throws IOException {
		// aiVsAi(new MasterAi(), new MasterAi());
		// humanvsai();
		aiVsServer(new MasterAi3());
	}

	private static void aiVsServer(Ai ai) throws IOException {

		while (true) {
			Client net = new Client("imcs.svcs.cs.pdx.edu", "3589",
					"piecemaster", "foobar");
			Board board = new Board();

			// Join or open a game
			String[] gameList = getGameList(net);

			for (int i = 0; i < gameList.length; i++) {
				System.out.println("### Line " + i + " = " + gameList[i]);
			}

			int rowNum = 0;
			String gameId = null;
			String enemyName = null;
			while (gameId == null && rowNum < gameList.length) {
				String[] row = gameList[rowNum].trim().split(" ");
				if (row.length >= 7 && "[offer]".equals(row[6])) {
					String[] splittedRow = gameList[rowNum].trim().split(" ");
					gameId = splittedRow[0];
					enemyName = splittedRow[1];
				}
				rowNum++;
			}

			char ownColor = '?';
			if (gameId != null) {
				System.out.println("### Connected to GameID: " + gameId);
				System.out.println("### Playing against: " + enemyName);
				ownColor = net.accept(gameId, ownColor);
			} else {
				net.offer('W');
				ownColor = 'W';
			}

			// Play the game until we are disconnected
			try {
				if (ownColor == 'B') {
					System.out.println("### Getting opponent's move ...");
					board.move(net.getMove());
				}
				Board.MoveResult result = Board.MoveResult.OK;
				while (result == Board.MoveResult.OK
						|| result == Board.MoveResult.ILLEGAL) {
					System.out.println("### Board BEFORE our draw:");
					System.out.println(board.toString());
					System.out.println("###################");
					Move move = ai.draw(board, board.getColor());
					System.out.println("### Our move: " + move.toString()
							+ " (We're "
							+ (ownColor == 'W' ? "White" : "Black")
							+ " playing against " + enemyName + ")");
					result = board.move(move);
					if (result == Board.MoveResult.ILLEGAL)
						System.out
								.println("################### ILLEGAL MOVE BY OURSELVES!");
					System.out.println("### Board AFTER our draw:");
					System.out.println(board.toString());
					System.out.println("###################");
					System.out.println("### Sending our move ...");
					net.sendMove(move.toString());
					System.out.println("### Waiting for opponent's move ...");
					String opponentMove = net.getMove();
					System.out.println("### Opponent's move: " + opponentMove);
					result = board.move(opponentMove);
					if (result == Board.MoveResult.ILLEGAL)
						System.out
								.println("################### ILLEGAL MOVE BY OPPONENT!");
				}
				switch (result) {
				case DRAW:
					System.out.println("################### DRAW!");
					break;
				case WIN_W:
					System.out.println("################### WHITE WINS!");
					break;
				case WIN_B:
					System.out.println("################### BLACK WINS!");
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static String[] getGameList(Client net) throws IOException {
		net.send("list", true);
		String strResponse = new String();
		do {
			String strRead = net.in.readLine();
			strResponse += strRead + "\n";

			if (strRead.equals(".") == true) {
				break;
			}
		} while (true);
		return strResponse.split("\n");
	}

	private static void humanvsai() {
		Board.MoveResult result = Board.MoveResult.OK;
		RandomAi rai = new RandomAi();
		Board board = new Board();
		char color = board.getColor();

		while (result == Board.MoveResult.OK) {
			System.out.println(board.toString());
			System.out.println("please insert move: ");
			do {
				result = board.move(readString());
				if (color == board.getColor() && result == Board.MoveResult.OK)
					System.out.println("wrong input try again: ");
			} while (color == board.getColor() && result == Board.MoveResult.OK);
			if (result == Board.MoveResult.OK)
				board.move(rai.draw(board, board.getColor()));
		}
		if (result == Board.MoveResult.WIN_B)
			System.out.println("hurra black hat gewonnen");
		if (result == Board.MoveResult.WIN_W)
			System.out.println("hurra white hat gewonnen");
		if (result == Board.MoveResult.DRAW)
			System.out.println("draw");
	}

	/**
	 * 
	 * @param ai1
	 *            White Ai
	 * @param ai2
	 *            Black Ai
	 */
	private static void aiVsAi(Ai ai1, Ai ai2) {
		RandomAi rai = new RandomAi();
		Board board = new Board();
		Move mov;
		for (int i = 0; i < 40; i++) { // einfach mal 5 züge
			// System.out.println("Bitte gib deinen Zug ein: ");
			// board.move(readString());
			System.out.println(board.toString());
			mov = rai.draw(board, board.getColor());
			System.out.println("mache Zug: " + mov.toString());
			board.move(rai.draw(board, board.getColor()));
		}
	}

	public static String readString() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));
			String s = in.readLine();
			return s; // Gelesenen String zurückgeben
		} catch (IOException ex) {
			System.out.println(ex.getMessage());
		}
		return "- Nichts gelesen -";
	}
}
